package com.pig4cloud.pig.order.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;

import com.pig4cloud.pig.order.api.dto.TrOrder;
import com.pig4cloud.pig.order.service.OrderService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.apache.http.HttpHeaders;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequiredArgsConstructor
@RequestMapping("/order")
@Tag(description = "order",name="订单管理")
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class OrderController {
	private final OrderService orderService;
	/**
	 * 分页查询
	 * @param page 分页对象
	 * @param order order 表
	 * @return
	 */
	@Operation(summary = "分页查询",description = "分页查询,地陪只能看见自己的订单")
	@GetMapping("/page")
	public R getOrderPage(@ParameterObject Page page,@ParameterObject TrOrder order){
		Long currentGuideId =1L;
		return R.ok(orderService.selectOrderPage(page,order,currentGuideId));
	}
	/**
	 * 查询全部订单
	 */
	@GetMapping("/list")
	public R<List<TrOrder>> listOrders(@ParameterObject TrOrder order){
		//当前登录的地陪ID
		Long currentGuideId =1L;
		return R.ok(orderService.selectOrderList(order,currentGuideId));
	}
	/**
	 * 查询订单信息
	 * @param order 查询条件
	 * @return R
	 */
	@Operation(description = "查询角色信息")
	@GetMapping("/details")
	public R getDetails(TrOrder order){
		return R.ok(orderService.getOne(Wrappers.query(order),false));
	}
	/**
	 * 通过id查询行程单表
	 * @param orderId id
	 * @return R
	 */
	@Operation(summary = "通过id查询行程单",description = "通过id查询行程单")
	@GetMapping("/trip/{orderId}")
	public R getById(@PathVariable("orderId" ) Integer orderId) {
		TrOrder order=orderService.getById(orderId);
		if(order ==null){
			return R.failed("订单不存在");
		}
		return R.ok(order);
	}

	/**
	 * 订单状态修改
	 * @param order
	 * @return
	 */
	@Transactional//添加事务注解，确保更新失败时回滚，成功时提交
	@Operation(summary = "订单状态变更",description = "未开始，进行中，已结束")
	@PutMapping("/status")
	public R updateOrderStatus(@RequestBody TrOrder order){
		try {
			TrOrder order1=orderService.selectByIdWithTrip(order.getOrderId());
			if(order1==null){
				return R.failed("订单不存在");
			}
			String newStatus=order.getOrStatus();//前段传入的目前值
			String oldStatus=order1.getOrStatus();//数据库当前状态
			boolean statusChanged = false;
			if("1".equals(newStatus) && "0".equals(oldStatus)){
				//开始按钮
				order1.setOrStatus(newStatus);
				statusChanged = true;
			}else if("2".equals(newStatus) && "1".equals(oldStatus)){
				order1.setOrStatus(newStatus);
				statusChanged = true;
			}else if(newStatus.equals(oldStatus)){
				statusChanged = false; // 状态不变
			}else{
				return R.failed("状态转换不合法");
			}

			//地陪都能写跟进
			if (StrUtil.isNotBlank(order.getRemark())) {
				String oldLabel = getStatusLabel(oldStatus);
				String newLabel = getStatusLabel(newStatus);
				String prefix = statusChanged ?
						"【状态变更：" + oldLabel + "=>" + newLabel + "】" :
						"【跟进】";
				String oldRemark = StrUtil.isBlank(order1.getRemark()) ? "" : order1.getRemark() + ";";
				order1.setRemark(oldRemark + prefix + order.getRemark());
			}
			int updateSuccess=orderService.updateStatusById(order1);
			if(updateSuccess ==  0){
				return R.failed("状态更新失败");
			}
			return  R.ok();
		} catch (Exception e) {
			e.printStackTrace(); // 打印异常日志
			return R.failed("服务器处理失败：" + e.getMessage());
		}
	}
	private String getStatusLabel(String statusValue) {
		switch (statusValue) {
			case "0":
				return "未开始";
			case "1":
				return "进行中";
			case "2":
				return "已结束";
			default:
				return "未知状态";
		}
	}

}
